<template>
	<view class="container">
		<!-- 上半部分：地图 -->
		<view class="map-section">
			<map class="map" :longitude="location.longitude" :latitude="location.latitude" :markers="markers"
				:polyline="trails" :scale="scale" :show-location="true" :enable-rotate="true" :enable-overlooking="true"
				:enable-3D="true" @regionchange="onRegionChange" @tap="onMapTap" @markertap="onMarkerTap">
				<!-- 加入地图交互配置信息 -->
				<cover-view class="sync-status" v-if="isSyncing">
					<text>正在同步数据...</text>
				</cover-view>
			</map>

			<!-- 地图控制按钮 -->
			<view class="map-controls">
				<view class="control-btn" @tap="zoomIn">
					<!-- <text class="iconfont icon-plus">+</text> -->
					<text>+</text>
				</view>
				<view class="control-btn" @tap="zoomOut">
					<!-- <text class="iconfont icon-minus"></text> -->
					<text>-</text>
				</view>
				<view class="control-btn" @tap="locateUser">
					<!-- <text class="iconfont icon-location"></text> -->
					<image style="width: 24px;height: 24px;" src="/static/map/location.png" mode=""></image>
				</view>
			</view>

			<!-- 离线模式提示 -->
			<view class="offline-indicator" v-if="isOffline">
				<text>离线模式</text>
			</view>
		</view>

		<!-- 下半部分：操作面板 -->
		<view class="control-section">
			<view class="tab-bar">
				<view class="tab-item" :class="{ active: activeTab === 'track' }" @tap="switchTab('track')">
					<text class="iconfont icon-track"></text>
					<text>轨迹</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'offline' }" @tap="switchTab('offline')">
					<text class="iconfont icon-offline"></text>
					<text>离线</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'friends' }" @tap="switchTab('friends')">
					<text class="iconfont icon-friends"></text>
					<text>同伴</text>
				</view>
			</view>

			<!-- 轨迹面板 -->
			<view class="panel-content" v-if="activeTab === 'track'">
				<view v-if="isRecording">
					<view class="data-row">
						<view class="data-item">
							<text class="data-value">{{ formatDistance(distance) }}</text>
							<text class="data-label">距离</text>
						</view>
						<view class="data-item">
							<text class="data-value">{{ formatDuration(duration) }}</text>
							<text class="data-label">时间</text>
						</view>
						<view class="data-item">
							<text class="data-value">{{ calculatePace() }}</text>
							<text class="data-label">配速</text>
						</view>
					</view>

					<view class="action-row">
						<button class="action-btn secondary" @tap="pauseRecording" v-if="!isPaused">暂停</button>
						<button class="action-btn primary" @tap="resumeRecording" v-if="isPaused">继续</button>
						<button class="action-btn danger" @tap="stopRecording">结束</button>
					</view>
				</view>

				<view v-else>
					<view class="start-hint">
						<text>点击"开始"按钮开始记录轨迹</text>
					</view>
					<button class="action-btn primary start-btn" @tap="startRecording">开始</button>

					<view class="history-section">
						<text class="section-title">历史轨迹</text>
						<scroll-view scroll-y class="history-list">
							<view class="history-item" v-for="track in savedTracks" :key="track.id"
								@tap="loadTrack(track)">
								<view class="track-info">
									<text class="track-date">{{ formatDate(track.date) }}</text>
									<text class="track-distance">{{ formatDistance(track.distance) }}</text>
								</view>
								<text class="iconfont icon-arrow-right"></text>
							</view>
						</scroll-view>
					</view>
				</view>
			</view>

			<!-- 离线地图面板 -->
			<view class="panel-content" v-if="activeTab === 'offline'">
				<view class="offline-status">
					<text class="section-title">离线地图</text>
					<view class="offline-toggle">
						<switch :checked="isOffline" @change="toggleOfflineMode" color="#007AFF" />
						<text>{{ isOffline ? '已启用' : '已禁用' }}</text>
					</view>
				</view>

				<view class="offline-actions">
					<button class="action-btn primary" @tap="saveCurrentMapArea">保存当前地图</button>
					<button class="action-btn secondary" @tap="manageOfflineMaps">管理离线地图</button>
				</view>

				<view class="offline-list" v-if="offlineMaps.length > 0">
					<text class="section-title">已保存的地图</text>
					<scroll-view scroll-y class="map-list">
						<view class="map-item" v-for="map in offlineMaps" :key="map.id">
							<view class="map-info">
								<text class="map-name">{{ map.name }}</text>
								<text class="map-size">{{ formatSize(map.size) }}</text>
							</view>
							<button class="delete-btn" @tap="deleteOfflineMap(map.id)">删除</button>
						</view>
					</scroll-view>
				</view>
			</view>

			<!-- 同伴面板 -->
			<view class="panel-content" v-if="activeTab === 'friends'">
				<view class="friends-header">
					<text class="section-title">附近同伴</text>
					<text class="refresh-btn" @tap="refreshNearbyFriends">刷新</text>
				</view>

				<scroll-view scroll-y class="friends-list">
					<view class="friend-item" v-for="friend in nearbyFriends" :key="friend.id">
						<image :src="friend.avatar" class="friend-avatar"></image>
						<view class="friend-info">
							<text class="friend-name">{{ friend.name }}</text>
							<text class="friend-distance">{{ formatDistance(friend.distance) }}</text>
						</view>
						<button class="action-btn small" @tap="sendMessage(friend)">消息</button>
					</view>
				</scroll-view>

				<view class="no-friends" v-if="nearbyFriends.length === 0">
					<text>暂无附近同伴</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	computed,
	onMounted,
	onUnmounted
} from '../../hooks';
import * as storageService from '../../services/storageService';
import * as cloudMapService from '../../services/cloudMapService';

// 同步状态
const isSyncing = ref(false);

// 离线模式状态
const isOffline = ref(false);
const isEditingTrack = ref(false);
const editingTrackId = ref(null);
const originalTrackPoints = ref([]); // 备份编辑前的轨迹点
const selectedTrack = ref(null);

// 地图数据
const location = ref({
	longitude: 116.39722,
	latitude: 39.9075,
});
const scale = ref(16);
const markers = ref([]);
const trails = ref([]);

// 记录状态
const isRecording = ref(false);
const isPaused = ref(false);
const distance = ref(0); // 单位：米
const duration = ref(0); // 单位：秒
const recordingInterval = ref(null);
const locationUpdateInterval = ref(null);
const recordedLocations = ref([]);

// 推荐路线
const routes = ref([{
	id: 1,
	name: '城市公园健步道',
	distance: 5.2,
	image: '/static/route1.png',
	path: [] // 路线坐标点
},
{
	id: 2,
	name: '滨海风景跑道',
	distance: 3.8,
	image: '/static/route2.png',
	path: [] // 路线坐标点
}
]);

// 控制面板展开状态
const isPanelExpanded = ref(false);
const selectedRouteId = ref(null);

// 新增数据属性
const activeTab = ref('track'); // 当前激活的标签页
const savedTracks = ref([]); // 保存的轨迹列表
const offlineMaps = ref([]); // 离线地图列表
const nearbyFriends = ref([]); // 附近的同伴列表

// 新增状态变量
const locationUpdateTimer = ref(null);

// 页面加载时
onMounted(async () => {
	// 检查网络状态
	const online = await cloudMapService.isOnline();

	// 检查是否处于离线模式
	isOffline.value = storageService.isOfflineMode() || !online;

	// 根据离线模式决定如何加载数据
	if (isOffline.value) {
		loadOfflineData();
	} else {
		// 获取当前位置
		getLocation();

		// 尝试同步本地数据到云端
		syncLocalDataToCloud();

		// 初始更新位置到云端
		updateInitialLocation();
	}

	// 加载保存的轨迹
	loadSavedTracks();

	// 加载离线地图列表
	loadOfflineMaps();

	// 刷新附近同伴
	refreshNearbyFriends();

	// 检查是否有路线参数
	const query = uni.getLaunchOptionsSync().query;
	if (query && query.routeId) {
		selectedRouteId.value = parseInt(query.routeId);
		const route = routes.value.find(r => r.id === selectedRouteId.value);
		if (route && route.path.length > 0) {
			showRouteOnMap(route);
		}
	}

	// 启动位置定期更新
	startLocationUpdates();

	// 设置网络监听
	setupNetworkListener();
});

// 页面卸载时
onUnmounted(() => {
	// 清除所有定时器
	clearIntervals();

	// 停止位置更新
	stopLocationUpdates();

	// 设置离线状态
	cloudMapService.setStatus('offline').catch(e => {
		console.error('设置离线状态失败:', e);
	});
});

// 清除所有定时器
const clearIntervals = () => {
	if (recordingInterval.value) {
		clearInterval(recordingInterval.value);
		recordingInterval.value = null;
	}

	if (locationUpdateInterval.value) {
		clearInterval(locationUpdateInterval.value);
		locationUpdateInterval.value = null;
	}
};

// 检查并请求位置权限
const checkAndRequestLocationPermission = () => {
	return new Promise((resolve, reject) => {
		// 检查权限状态
		uni.getSetting({
			success: (res) => {
				// 如果已经授权，直接返回成功
				if (res.authSetting['scope.userLocation']) {
					resolve(true);
					return;
				}

				// 如果未授权，请求授权
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						resolve(true);
					},
					fail: (err) => {
						// 用户拒绝授权，引导用户到设置页面
						uni.showModal({
							title: '位置权限',
							content: '需要获取您的位置信息，请授予"位置信息"权限',
							confirmText: '去设置',
							cancelText: '取消',
							success: (res) => {
								if (res.confirm) {
									// 打开设置页面
									uni.openSetting({
										success: (settingRes) => {
											if (settingRes.authSetting['scope.userLocation']) {
												resolve(true);
											} else {
												reject('用户拒绝授权位置信息');
											}
										},
										fail: () => {
											reject('打开设置页面失败');
										}
									});
								} else {
									reject('用户取消授权位置信息');
								}
							}
						});
					}
				});
			},
			fail: (err) => {
				reject('获取设置信息失败');
			}
		});
	});
};

// 获取当前位置
const getLocation = async () => {
	try {
		// 先检查和请求权限
		await checkAndRequestLocationPermission();

		// 获取位置
		uni.getLocation({
			type: 'gcj02',
			success: res => {
				location.value.longitude = res.longitude;
				location.value.latitude = res.latitude;

				// 添加当前位置标记
				markers.value = [{
					id: 0,
					latitude: res.latitude,
					longitude: res.longitude,
					iconPath: '/static/location.png',
					width: 30,
					height: 30
				}];
			},
			fail: (err) => {
				console.error('获取位置失败:', err);
				uni.showToast({
					title: '获取位置失败，请检查位置服务是否开启',
					icon: 'none'
				});
			}
		});
	} catch (err) {
		console.error('位置权限错误:', err);
		uni.showToast({
			title: '未获得位置权限，部分功能可能受限',
			icon: 'none'
		});
	}
};

// 开始记录
const startRecording = async () => {
	// 重置数据
	distance.value = 0;
	duration.value = 0;
	recordedLocations.value = [];
	isRecording.value = true;
	isPaused.value = false;

	try {
		// 先检查和请求权限
		await checkAndRequestLocationPermission();

		// 记录开始位置
		uni.getLocation({
			type: 'gcj02',
			success: res => {
				const startLocation = {
					latitude: res.latitude,
					longitude: res.longitude,
					timestamp: Date.now()
				};

				recordedLocations.value.push(startLocation);

				// 更新轨迹
				updateTrail();

				// 开始计时
				recordingInterval.value = setInterval(() => {
					duration.value++;
				}, 1000);

				// 定期更新位置和距离
				locationUpdateInterval.value = setInterval(() => {
					if (!isPaused.value) {
						updateLocation();
					}
				}, 3000); // 每3秒更新一次位置
			},
			fail: (err) => {
				console.error('获取位置失败:', err);
				uni.showToast({
					title: '获取位置失败，请检查位置服务是否开启',
					icon: 'none'
				});
				isRecording.value = false;
			}
		});
	} catch (err) {
		console.error('位置权限错误:', err);
		uni.showToast({
			title: '未获得位置权限，无法开始记录',
			icon: 'none'
		});
		isRecording.value = false;
	}
};

// 更新位置
const updateLocation = async () => {
	try {
		// 每次更新前确保有权限
		await checkAndRequestLocationPermission();

		uni.getLocation({
			type: 'gcj02',
			success: res => {
				const newLocation = {
					latitude: res.latitude,
					longitude: res.longitude,
					timestamp: Date.now()
				};

				// 更新当前位置
				location.value.longitude = res.longitude;
				location.value.latitude = res.latitude;

				// 更新标记位置
				markers.value[0].latitude = res.latitude;
				markers.value.forEach(marker => {
					if (marker.pointIndex !== undefined) {
						marker.latitude = res.latitude;
						marker.longitude = res.longitude;
					}
				});

				// 计算与上一个点的距离
				if (recordedLocations.value.length > 0) {
					const lastLocation = recordedLocations.value[recordedLocations.value.length - 1];
					const segmentDistance = calculateDistance(
						lastLocation.latitude,
						lastLocation.longitude,
						newLocation.latitude,
						newLocation.longitude
					);

					// 如果与上一个点距离过近，则不记录(防抖)
					if (segmentDistance > 2) { // 最小2米
						recordedLocations.value.push(newLocation);
						distance.value += segmentDistance;
						updateTrail();
					}
				}
			}
		});
	} catch (err) {
		console.error('位置权限错误:', err);
		uni.showToast({
			title: '未获得位置权限，无法更新位置',
			icon: 'none'
		});
	}
};

// 更新轨迹
const updateTrail = () => {
	if (recordedLocations.value.length < 2) return;

	const points = recordedLocations.value.map(loc => ({
		latitude: loc.latitude,
		longitude: loc.longitude
	}));

	trails.value = [{
		points: points,
		color: '#007AFF',
		width: 6
	}];
};

// 暂停记录
const pauseRecording = () => {
	isPaused.value = true;
};

// 继续记录
const resumeRecording = () => {
	isPaused.value = false;
};

// 停止记录
const stopRecording = () => {
	uni.showModal({
		title: '结束运动',
		content: '确定要结束本次运动吗？',
		success: res => {
			if (res.confirm) {
				clearIntervals();

				// 在离线模式下，确保将数据保存到本地
				if (isOffline.value) {
					uni.showToast({
						title: '正在保存数据到本地',
						icon: 'loading',
						duration: 1000
					});
				}

				// 保存轨迹数据
				saveTrackData();

				// 重置状态
				isRecording.value = false;
				isPaused.value = false;
			}
		}
	});
};

// 保存轨迹数据
const saveTrackData = async () => {
	// 构建轨迹数据
	const trackData = {
		distance: distance.value,
		duration: duration.value,
		date: new Date(),
		locations: recordedLocations.value
	};

	let trackId;

	// 根据离线模式决定保存方式
	if (isOffline.value) {
		// 离线模式下保存到本地
		trackId = storageService.saveTrackData(trackData);
	} else {
		// 在线模式下尝试保存到云端
		try {
			trackId = await cloudMapService.saveTrackData(trackData);
		} catch (e) {
			console.error('保存到云端失败，回退到本地保存:', e);
			trackId = storageService.saveTrackData(trackData);
		}
	}

	// 重新加载轨迹列表
	loadSavedTracks();

	// 显示保存成功提示
	uni.showToast({
		title: '轨迹已保存',
		icon: 'success',
		duration: 2000
	});

	// 跳转到结果页
	uni.navigateTo({
		url: `/pages/track-result/track-result?distance=${distance.value}&duration=${duration.value}&trackId=${trackId}`
	});
};

// 计算两点之间的距离（米）
const calculateDistance = (lat1, lon1, lat2, lon2) => {
	const R = 6371000; // 地球半径，单位米
	const dLat = (lat2 - lat1) * Math.PI / 180;
	const dLon = (lon2 - lon1) * Math.PI / 180;
	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		Math.sin(dLon / 2) * Math.sin(dLon / 2);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	return R * c;
};

// 格式化距离
const formatDistance = (meters) => {
	if (meters < 1000) {
		return meters.toFixed(0) + 'm';
	} else {
		return (meters / 1000).toFixed(2) + 'km';
	}
};

// 格式化时间
const formatDuration = (seconds) => {
	const hours = Math.floor(seconds / 3600);
	const minutes = Math.floor((seconds % 3600) / 60);
	const secs = seconds % 60;

	if (hours > 0) {
		return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
	} else {
		return `${minutes}:${secs.toString().padStart(2, '0')}`;
	}
};

// 计算配速（分钟/公里）
const calculatePace = () => {
	if (distance.value <= 0) return '--\'--\"';

	const paceSeconds = (duration.value / (distance.value / 1000));
	const paceMinutes = Math.floor(paceSeconds / 60);
	const paceRemainder = Math.floor(paceSeconds % 60);

	return `${paceMinutes}'${paceRemainder.toString().padStart(2, '0')}\"`;
};

// 地图缩放
const zoomIn = () => {
	if (scale.value < 20) {
		scale.value++;
	}
};

const zoomOut = () => {
	if (scale.value > 3) {
		scale.value--;
	}
};

// 定位到用户
const locateUser = () => {
	getLocation();
};

// 切换面板展开状态
const togglePanel = () => {
	isPanelExpanded.value = !isPanelExpanded.value;
};

// 选择路线
const selectRoute = (route) => {
	selectedRouteId.value = route.id === selectedRouteId.value ? null : route.id;

	if (selectedRouteId.value !== null) {
		showRouteOnMap(route);
	} else {
		// 清除路线
		trails.value = [];
	}
};

// 在地图上显示路线
const showRouteOnMap = (route) => {
	// 实际应用中应该从API获取路线坐标
	// 这里简单模拟一下
	if (route.path.length === 0) {
		// 生成虚拟路径点
		const baseLat = location.value.latitude;
		const baseLng = location.value.longitude;
		const points = [];

		for (let i = 0; i < 10; i++) {
			points.push({
				latitude: baseLat + (Math.random() - 0.5) * 0.01,
				longitude: baseLng + (Math.random() - 0.5) * 0.01
			});
		}

		route.path = points;
	}

	trails.value = [{
		points: route.path,
		color: '#FF6B6B',
		width: 6,
		dottedLine: true
	}];
};

// 地图区域变化事件
const onRegionChange = (e) => {
	// 可以在这里处理地图区域变化事件
};

// 地图点击事件
const onMapTap = (e) => {
	if (!isEditingTrack.value || activeMarkerIndex.value === null) return;

	const newLocation = e.detail;

	// 更新标记点位置
	markers.value.forEach(marker => {
		if (marker.pointIndex === activeMarkerIndex.value) {
			marker.latitude = newLocation.latitude;
			marker.longitude = newLocation.longitude;
		}
	});

	// 更新轨迹线
	if (selectedTrack.value && selectedTrack.value.locations) {
		selectedTrack.value.locations[activeMarkerIndex.value] = {
			...selectedTrack.value.locations[activeMarkerIndex.value],
			latitude: newLocation.latitude,
			longitude: newLocation.longitude
		};

		const points = selectedTrack.value.locations.map(loc => ({
			latitude: loc.latitude,
			longitude: loc.longitude
		}));

		trails.value = [{
			points: points,
			color: '#007AFF',
			width: 6
		}];
	}

	// 重置编辑点
	activeMarkerIndex.value = null;

	uni.showToast({
		title: '轨迹点已移动',
		icon: 'success',
		duration: 1000
	});
};

// 离线模式切换
const toggleOfflineMode = async (e) => {
	isOffline.value = e.detail.value;
	storageService.setOfflineMode(isOffline.value);

	// 更新在线状态
	if (!isOffline.value) {
		// 切换到在线模式
		try {
			await cloudMapService.setStatus('online');
		} catch (e) {
			console.error('更新在线状态失败:', e);
		}
	} else {
		// 切换到离线模式
		try {
			await cloudMapService.setStatus('offline');
		} catch (e) {
			console.error('更新离线状态失败:', e);
		}
	}

	if (isOffline.value) {
		// 切换到离线模式
		loadOfflineData();
	} else {
		// 尝试连接网络
		const online = await cloudMapService.isOnline();
		if (!online) {
			uni.showToast({
				title: '无网络连接，将保持离线模式',
				icon: 'none',
				duration: 2000
			});
			isOffline.value = true;
			storageService.setOfflineMode(true);
			return;
		}

		// 切换到在线模式
		getLocation();

		// 尝试同步本地数据到云端
		syncLocalDataToCloud();

		// 重新加载数据
		loadSavedTracks();
		loadOfflineMaps();
	}
};

// 监听网络状态变化
const setupNetworkListener = () => {
	uni.onNetworkStatusChange(async (res) => {
		const online = res.isConnected;

		if (online && isOffline.value) {
			// 如果网络恢复且处于离线模式，询问是否切换到在线模式
			uni.showModal({
				title: '网络已恢复',
				content: '是否切换到在线模式并同步数据？',
				success: (modalRes) => {
					if (modalRes.confirm) {
						isOffline.value = false;
						storageService.setOfflineMode(false);

						// 同步数据
						syncLocalDataToCloud();

						// 重新加载数据
						loadSavedTracks();
						loadOfflineMaps();
					}
				}
			});
		} else if (!online && !isOffline.value) {
			// 如果网络断开且处于在线模式，提示并切换到离线模式
			uni.showToast({
				title: '网络连接断开，已切换至离线模式',
				icon: 'none',
				duration: 2000
			});

			isOffline.value = true;
			storageService.setOfflineMode(true);
		}
	});
};

// 加载离线数据
const loadOfflineData = () => {
	// 加载保存的地图区域
	const savedMapArea = storageService.getSavedMapArea();
	if (savedMapArea) {
		location.value.longitude = savedMapArea.longitude;
		location.value.latitude = savedMapArea.latitude;
		scale.value = savedMapArea.scale;

		// 添加当前位置标记
		markers.value = [{
			id: 0,
			latitude: savedMapArea.latitude,
			longitude: savedMapArea.longitude,
			iconPath: '/static/location.png',
			width: 30,
			height: 30
		}];
	}

	// 提示用户处于离线模式
	uni.showToast({
		title: '当前处于离线模式',
		icon: 'none',
		duration: 2000
	});
};

// 保存当前地图区域以供离线使用
const saveCurrentMapArea = async () => {
	const currentRegion = {
		name: `离线地图 ${new Date().toLocaleString()}`,
		latitude: location.value.latitude,
		longitude: location.value.longitude,
		scale: scale.value,
		size: 1024 * 1024 // 假设大小，实际应基于地图区域计算
	};

	let success = false;
	try {
		if (isOffline.value) {
			// 离线模式下保存到本地
			success = storageService.saveMapArea(currentRegion);

			if (success) {
				// 同时保存到离线地图列表
				storageService.saveOfflineMap(currentRegion);
			}
		} else {
			// 在线模式下尝试保存到云端
			const mapId = await cloudMapService.saveOfflineMap(currentRegion);
			success = !!mapId;

			// 保存基本信息到本地，以支持离线模式
			if (success) {
				storageService.saveMapArea(currentRegion);
			}
		}

		// 重新加载离线地图列表
		loadOfflineMaps();

		if (success) {
			uni.showToast({
				title: '已保存当前地图区域',
				icon: 'success',
				duration: 2000
			});
		} else {
			uni.showToast({
				title: '保存地图区域失败',
				icon: 'none',
				duration: 2000
			});
		}
	} catch (e) {
		console.error('保存地图区域出错:', e);
		uni.showToast({
			title: '保存地图区域失败',
			icon: 'none',
			duration: 2000
		});
	}
};

// 加载保存的轨迹
const loadSavedTracks = async () => {
	if (isOffline.value) {
		// 离线模式下从本地加载
		savedTracks.value = storageService.getSavedTracks();
	} else {
		// 在线模式下从云端加载
		try {
			const result = await cloudMapService.getTrackList();
			if (result && result.list) {
				savedTracks.value = result.list;
			}
		} catch (e) {
			console.error('从云端加载轨迹失败，回退到本地加载:', e);
			savedTracks.value = storageService.getSavedTracks();
		}
	}
};

// 显示保存的轨迹
const displaySavedTrack = (track) => {
	if (!track || !track.locations || track.locations.length < 2) {
		uni.showToast({
			title: '轨迹数据不完整',
			icon: 'none',
			duration: 2000
		});
		return;
	}

	// 显示轨迹点
	const points = track.locations.map(loc => ({
		latitude: loc.latitude,
		longitude: loc.longitude
	}));

	// 添加轨迹起点和终点标记
	markers.value = [{
		id: 0,
		latitude: location.value.latitude,
		longitude: location.value.longitude,
		iconPath: '/static/location.png',
		width: 30,
		height: 30
	},
	{
		id: 1,
		latitude: points[0].latitude,
		longitude: points[0].longitude,
		iconPath: '/static/start.png',
		width: 24,
		height: 24
	},
	{
		id: 2,
		latitude: points[points.length - 1].latitude,
		longitude: points[points.length - 1].longitude,
		iconPath: '/static/finish.png',
		width: 24,
		height: 24
	}
	];

	// 添加轨迹中间点标记，用于编辑
	for (let i = 1; i < points.length - 1; i += Math.ceil(points.length / 10)) { // 仅显示部分标记，避免过多
		markers.value.push({
			id: i + 2,
			latitude: points[i].latitude,
			longitude: points[i].longitude,
			iconPath: '/static/waypoint.png',
			width: 16,
			height: 16,
			anchor: {
				x: 0.5,
				y: 0.5
			},
			pointIndex: i // 用于标识是哪个轨迹点
		});
	}

	// 设置轨迹线
	trails.value = [{
		points: points,
		color: '#007AFF',
		width: 6
	}];

	// 将地图视图调整到轨迹范围
	adjustMapViewToFitTrack(points);
};

// 调整地图视图以适应轨迹
const adjustMapViewToFitTrack = (points) => {
	if (!points || points.length === 0) return;

	// 找出轨迹的经纬度范围
	let minLat = points[0].latitude;
	let maxLat = points[0].latitude;
	let minLng = points[0].longitude;
	let maxLng = points[0].longitude;

	points.forEach(point => {
		minLat = Math.min(minLat, point.latitude);
		maxLat = Math.max(maxLat, point.latitude);
		minLng = Math.min(minLng, point.longitude);
		maxLng = Math.max(maxLng, point.longitude);
	});

	// 计算中心点
	const centerLat = (minLat + maxLat) / 2;
	const centerLng = (minLng + maxLng) / 2;

	// 设置地图中心点
	location.value.latitude = centerLat;
	location.value.longitude = centerLng;

	// 计算合适的缩放级别
	// 简单实现，具体应该根据地图API有更精确的计算方法
	const latDiff = maxLat - minLat;
	const lngDiff = maxLng - minLng;
	const maxDiff = Math.max(latDiff, lngDiff);

	if (maxDiff > 0.1) scale.value = 10;
	else if (maxDiff > 0.05) scale.value = 12;
	else if (maxDiff > 0.01) scale.value = 14;
	else if (maxDiff > 0.005) scale.value = 15;
	else scale.value = 16;
};

// 开始编辑轨迹
const startEditTrack = (trackId) => {
	if (!selectedTrack.value) return;

	isEditingTrack.value = true;
	editingTrackId.value = trackId;

	// 备份原始轨迹点，以便取消时恢复
	if (selectedTrack.value.locations) {
		originalTrackPoints.value = JSON.parse(JSON.stringify(selectedTrack.value.locations));
	}

	uni.showToast({
		title: '点击标记可移动轨迹点',
		icon: 'none',
		duration: 2000
	});
};

// 确认轨迹编辑
const confirmTrackEdit = async () => {
	if (!selectedTrack.value || !editingTrackId.value) return;

	// 根据当前地图上的markers更新轨迹点
	const updatedLocations = selectedTrack.value.locations;

	// 更新已编辑的轨迹点
	markers.value.forEach(marker => {
		if (marker.pointIndex !== undefined) {
			if (updatedLocations[marker.pointIndex]) {
				updatedLocations[marker.pointIndex].latitude = marker.latitude;
				updatedLocations[marker.pointIndex].longitude = marker.longitude;
			}
		}
	});

	// 重新计算轨迹距离
	let newDistance = 0;
	for (let i = 1; i < updatedLocations.length; i++) {
		newDistance += calculateDistance(
			updatedLocations[i - 1].latitude,
			updatedLocations[i - 1].longitude,
			updatedLocations[i].latitude,
			updatedLocations[i].longitude
		);
	}

	// 更新数据
	const updateData = {
		locations: updatedLocations,
		distance: newDistance
	};

	try {
		let success = false;

		if (isOffline.value) {
			// 离线模式下更新本地存储
			success = storageService.updateTrack(editingTrackId.value, updateData);
		} else {
			// 在线模式下更新云端数据
			success = await cloudMapService.updateTrack(editingTrackId.value, updateData);
		}

		if (success) {
			// 更新UI显示
			distance.value = newDistance;

			// 更新轨迹线
			const points = updatedLocations.map(loc => ({
				latitude: loc.latitude,
				longitude: loc.longitude
			}));

			trails.value = [{
				points: points,
				color: '#007AFF',
				width: 6
			}];

			uni.showToast({
				title: '轨迹已保存',
				icon: 'success',
				duration: 2000
			});
		} else {
			uni.showToast({
				title: '保存失败',
				icon: 'none',
				duration: 2000
			});
		}
	} catch (e) {
		console.error('更新轨迹失败:', e);
		uni.showToast({
			title: '保存失败',
			icon: 'none',
			duration: 2000
		});
	} finally {
		// 退出编辑模式
		isEditingTrack.value = false;
		editingTrackId.value = null;
	}
};

// 取消轨迹编辑
const cancelTrackEdit = () => {
	if (!selectedTrack.value) return;

	// 恢复原始轨迹点
	if (originalTrackPoints.value.length > 0) {
		selectedTrack.value.locations = originalTrackPoints.value;

		// 重新显示轨迹
		displaySavedTrack(selectedTrack.value);
	}

	// 退出编辑模式
	isEditingTrack.value = false;
	editingTrackId.value = null;

	uni.showToast({
		title: '已取消编辑',
		icon: 'none',
		duration: 2000
	});
};

// 处理标记点点击事件 - 用于移动轨迹点
const onMarkerTap = (e) => {
	const markerId = e.detail.markerId;
	const marker = markers.value.find(m => m.id === markerId);

	if (!marker || !isEditingTrack.value) return;

	// 如果是轨迹点（不是起点终点），允许编辑
	if (marker.pointIndex !== undefined) {
		// 显示拖动指示
		uni.showToast({
			title: '正在移动轨迹点，点击地图确定位置',
			icon: 'none',
			duration: 2000
		});

		// 设置当前正在编辑的点
		activeMarkerIndex.value = marker.pointIndex;
	}
};

// 用于保存当前正在编辑的点的索引
const activeMarkerIndex = ref(null);

// 切换标签页
const switchTab = (tab) => {
	activeTab.value = tab;
};

// 格式化日期
const formatDate = (date) => {
	const d = new Date(date);
	return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
};

// 格式化文件大小
const formatSize = (bytes) => {
	if (bytes < 1024) return bytes + 'B';
	if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
	return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
};

// 加载轨迹
const loadTrack = async (track) => {
	try {
		let trackDetail;

		if (isOffline.value) {
			// 离线模式下从本地加载详情
			trackDetail = storageService.getTrackById(track.id || track._id);
		} else {
			// 在线模式下从云端加载详情
			trackDetail = await cloudMapService.getTrackDetail(track.id || track._id);
		}

		if (!trackDetail) {
			uni.showToast({
				title: '加载轨迹失败',
				icon: 'none'
			});
			return;
		}

		selectedTrack.value = trackDetail;
		displaySavedTrack(trackDetail);
	} catch (e) {
		console.error('加载轨迹详情失败:', e);
		uni.showToast({
			title: '加载轨迹失败',
			icon: 'none'
		});
	}
};

// 管理离线地图
const manageOfflineMaps = async () => {
	// 重新加载离线地图列表
	await loadOfflineMaps();
};

// 删除离线地图
const deleteOfflineMap = async (mapId) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这个离线地图吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					let success = false;

					if (isOffline.value) {
						// 离线模式下从本地删除
						storageService.deleteOfflineMap(mapId);
						success = true;
					} else {
						// 在线模式下从云端删除
						success = await cloudMapService.deleteOfflineMap(mapId);
					}

					if (success) {
						// 重新加载离线地图列表
						loadOfflineMaps();

						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('删除离线地图失败:', e);
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					});
				}
			}
		}
	});
};

// 刷新附近同伴
const refreshNearbyFriends = async () => {
	try {
		// 先检查和请求权限
		await checkAndRequestLocationPermission();

		// 获取当前位置
		uni.getLocation({
			type: 'gcj02',
			success: async (res) => {
				const {
					latitude,
					longitude
				} = res;

				// 显示加载状态
				uni.showLoading({
					title: '正在获取附近同伴'
				});

				try {
					// 调用云服务获取附近同伴
					const friends = await cloudMapService.getNearbyFriends(latitude, longitude);

					if (friends && friends.length > 0) {
						nearbyFriends.value = friends;

						// 更新地图上的同伴标记
						updateFriendMarkers();

						uni.showToast({
							title: `已找到${friends.length}位附近的同伴`,
							icon: 'success'
						});
					} else {
						nearbyFriends.value = [];
						// 清除地图上的同伴标记
						markers.value = markers.value.filter(marker => !marker.isFriend);

						uni.showToast({
							title: '附近暂无同伴',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('获取附近同伴失败:', e);
					uni.showToast({
						title: '获取附近同伴失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			fail: (err) => {
				console.error('获取位置失败:', err);
				uni.showToast({
					title: '获取位置失败，请检查位置服务是否开启',
					icon: 'none'
				});
			}
		});
	} catch (err) {
		console.error('位置权限错误:', err);
		uni.showToast({
			title: '未获得位置权限，无法获取附近同伴',
			icon: 'none'
		});
	}
};

// 更新地图上的同伴标记
const updateFriendMarkers = () => {
	// 过滤掉非同伴的标记
	markers.value = markers.value.filter(marker => !marker.isFriend);

	// 添加同伴标记
	nearbyFriends.value.forEach(friend => {
		markers.value.push({
			id: `friend_${friend.id}`,
			latitude: friend.latitude,
			longitude: friend.longitude,
			iconPath: '/static/friend-marker.png',
			width: 30,
			height: 30,
			isFriend: true,
			callout: {
				content: friend.name,
				color: '#ffffff',
				fontSize: 12,
				borderRadius: 4,
				padding: 5,
				bgColor: '#007AFF',
				display: 'ALWAYS'
			}
		});
	});
};

// 发送消息给同伴
const sendMessage = (friend) => {
	uni.navigateTo({
		url: `/pages/chat/chat?friendId=${friend.id}&friendName=${friend.name}`
	});
};

// 同步本地数据到云端
const syncLocalDataToCloud = async () => {
	// 如果不是离线模式且有网络连接，尝试同步数据
	if (!isOffline.value) {
		isSyncing.value = true;
		try {
			const result = await cloudMapService.syncLocalDataToCloud();
			if (result.success) {
				console.log('数据同步成功:', result.message);
			} else {
				console.error('数据同步失败:', result.message);
			}
		} catch (e) {
			console.error('数据同步过程中出错:', e);
		} finally {
			isSyncing.value = false;
		}
	}
};

// 加载离线地图列表
const loadOfflineMaps = async () => {
	if (isOffline.value) {
		// 离线模式下从本地加载
		offlineMaps.value = storageService.getOfflineMaps();
	} else {
		// 在线模式下从云端加载
		try {
			const result = await cloudMapService.getOfflineMapList();
			if (result && result.list) {
				offlineMaps.value = result.list;
			}
		} catch (e) {
			console.error('从云端加载离线地图失败，回退到本地加载:', e);
			offlineMaps.value = storageService.getOfflineMaps();
		}
	}
};

// 周期性更新位置
const startLocationUpdates = () => {
	// 每1分钟更新一次位置
	locationUpdateTimer.value = setInterval(async () => {
		if (isOffline.value) return;

		try {
			// 检查权限
			await checkAndRequestLocationPermission();

			uni.getLocation({
				type: 'gcj02',
				success: async (res) => {
					// 更新位置到云端
					try {
						await cloudMapService.updateLocation(res.latitude, res.longitude);
					} catch (e) {
						console.error('更新位置失败:', e);
					}
				},
				fail: (err) => {
					console.error('获取位置失败:', err);
				}
			});
		} catch (err) {
			console.error('位置权限错误:', err);
		}
	}, 60 * 1000);
};

// 停止位置更新
const stopLocationUpdates = () => {
	if (locationUpdateTimer.value) {
		clearInterval(locationUpdateTimer.value);
		locationUpdateTimer.value = null;
	}
};

// 初始更新位置
const updateInitialLocation = async () => {
	if (isOffline.value) return;

	try {
		// 检查权限
		await checkAndRequestLocationPermission();

		uni.getLocation({
			type: 'gcj02',
			success: async (res) => {
				try {
					// 更新位置到云端
					await cloudMapService.updateLocation(res.latitude, res.longitude);
				} catch (e) {
					console.error('初始位置更新失败:', e);
				}
			},
			fail: (err) => {
				console.error('获取位置失败:', err);
			}
		});
	} catch (err) {
		console.error('位置权限错误:', err);
		uni.showToast({
			title: '未获得位置权限，无法更新位置信息',
			icon: 'none'
		});
	}
};
</script>

<style>
html,
body {
	height: 100vh;
	overflow: hidden;
}

.container {
	position: relative;
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
}

.map-section {
	position: relative;
	width: 100%;
	height: 60vh;
	/* 修改：固定为60%视窗高度 */
	flex: none;
	/* 修改：不使用flex伸缩 */
}

.map {
	width: 100%;
	height: 100%;
}

.control-section {
	width: 100%;
	height: 40vh;
	/* 修改：固定为40%视窗高度 */
	background-color: #fff;
	border-radius: 30rpx 30rpx 0 0;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	z-index: 100;
	display: flex;
	flex-direction: column;
	flex: none;
	/* 修改：不使用flex伸缩 */
}

.tab-bar {
	display: flex;
	justify-content: space-around;
	padding: 10rpx 0;
	background-color: #fff;
	border-radius: 30rpx 30rpx 0 0;
	position: sticky;
	/* 添加：使标签栏固定 */
	top: 0;
	/* 添加：固定在顶部 */
	z-index: 10;
	/* 添加：确保显示在内容上方 */
}

.tab-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 10rpx 0;
}

.tab-item.active {
	border-bottom: 2rpx solid #007AFF;
}

.tab-item text {
	font-size: 24rpx;
	color: #333;
	margin-top: 5rpx;
}

.panel-content {
	padding: 20rpx 30rpx;
	height: calc(40vh - 90rpx);
	/* 修改：减去tab-bar的高度 */
	overflow-y: auto;
	/* 修改：内容可滚动 */
	-webkit-overflow-scrolling: touch;
	/* 添加：增强iOS滚动体验 */
}

.data-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 30rpx;
}

.data-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.data-value {
	font-size: 40rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 5rpx;
}

.data-label {
	font-size: 24rpx;
	color: #999;
}

.action-row {
	display: flex;
	justify-content: space-around;
}

.action-btn {
	min-width: 180rpx;
	height: 80rpx;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
}

.primary {
	background-color: #007AFF;
	color: #fff;
}

.secondary {
	background-color: #6c757d;
	color: #fff;
}

.danger {
	background-color: #FF3B30;
	color: #fff;
}

.start-hint {
	text-align: center;
	color: #999;
	margin-bottom: 20rpx;
}

.start-btn {
	width: 60%;
	margin: 0 auto;
}

.map-controls {
	position: absolute;
	right: 30rpx;
	top: 50%;
	transform: translateY(-50%);
	z-index: 99;
}

.control-btn {
	width: 80rpx;
	height: 80rpx;
	background-color: #fff;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.control-btn text {
	font-size: 40rpx;
	color: #333;
}

.offline-indicator {
	position: absolute;
	top: 40rpx;
	left: 30rpx;
	background-color: rgba(255, 59, 48, 0.8);
	color: white;
	padding: 10rpx 20rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	z-index: 99;
}

.offline-status {
	margin-bottom: 30rpx;
}

.offline-toggle {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.offline-toggle switch {
	margin-right: 10rpx;
}

.offline-actions {
	display: flex;
	justify-content: space-around;
}

.small-btn {
	min-width: 120rpx;
	height: 60rpx;
	border-radius: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
}

.offline-list {
	margin-top: 30rpx;
	max-height: calc(40vh - 200rpx);
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
}

.map-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.map-info {
	display: flex;
	flex-direction: column;
}

.map-name {
	font-size: 24rpx;
	color: #333;
	margin-bottom: 5rpx;
}

.map-size {
	font-size: 20rpx;
	color: #999;
}

.delete-btn {
	background-color: #FF3B30;
	color: #fff;
	border: none;
	padding: 5rpx 10rpx;
	border-radius: 5rpx;
}

.friends-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.refresh-btn {
	background-color: #007AFF;
	color: #fff;
	border: none;
	padding: 5rpx 10rpx;
	border-radius: 5rpx;
}

.friends-list {
	max-height: calc(40vh - 200rpx);
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
}

.friend-item {
	display: flex;
	align-items: center;
	padding: 10rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.friend-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 10rpx;
}

.friend-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.friend-name {
	font-size: 24rpx;
	color: #333;
	margin-bottom: 5rpx;
}

.friend-distance {
	font-size: 20rpx;
	color: #999;
}

.no-friends {
	text-align: center;
	color: #999;
	margin-top: 20rpx;
}

.history-list {
	max-height: calc(40vh - 200rpx);
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
}
</style>